const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
const app = getApp();
let that;
Page({
  data: {
    ImgRootUrl: app.globalData.ImgRootUrl,
    address: {
      id: 0,
      accept_name: '', //姓名
      province: 0,     //省份
      city: 0,         //城市
      area: 0,         //区县
      full_region: '',    //省市区
      address: '',        //详细地址
      mobile: '',         //手机号
      is_default: 0       //1.默认地址；0非默认
    },
    addressId: 0,   //地址id
    openSelectRegion: false,  //打开、关闭（省市区选择弹窗）
    selectRegionList: [
      { area_id: 0, area_name: '省份', parent_id: 0, type: 1 },
      { area_id: 0, area_name: '城市', parent_id: 0, type: 2 },
      { area_id: 0, area_name: '区县', parent_id: 0, type: 3 }
    ],
    regionType: 1,  //当前省市区的 类型
    regionList: [],   //接口请求省市区[数组]
    selectRegionDone: false   //选择完毕
  },
  //手机
  bindinputMobile(event) {
    let address = this.data.address;
    address.mobile = event.detail.value;
    this.setData({
      address: address
    });
  },
  //姓名
  bindinputName(event) {
    let address = this.data.address;
    address.accept_name = event.detail.value;
    this.setData({
      address: address
    });
  },
  //详细地址
  bindinputAddress(event) {
    let address = this.data.address;
    address.address = event.detail.value;
    this.setData({
      address: address
    });
  },
  //是否默认
  bindIsDefault() {
    let address = this.data.address;
    address.is_default = address.is_default ? 0 : 1;
    this.setData({
      address: address
    });
  },
  //获取地址详情
  getAddressDetail() {
    util.request(api.AddressDetail, { id: that.data.addressId }).then(function (res) {
      if (res.errno === 0) {
        let address = res.data;
        let selectRegionList = that.data.selectRegionList;;
        selectRegionList[0].area_id = address.province;
        selectRegionList[0].area_name = address.province_name;
        selectRegionList[0].parent_id = 0;

        selectRegionList[1].area_id = address.city;
        selectRegionList[1].area_name = address.city_name;
        selectRegionList[1].parent_id = address.province;

        selectRegionList[2].area_id = address.area;
        selectRegionList[2].area_name = address.area_name;
        selectRegionList[2].parent_id = address.city;
        address.full_region = selectRegionList.map(item => {
          return item.area_name;
        }).join('');
        that.setData({
          selectRegionList: selectRegionList,
          address: address,
          regionType: 3
        });
      }
    });
  },
  //检查选择完毕？
  setRegionDoneStatus() {
    let doneStatus = that.data.selectRegionList.every(item => {
      return item.area_id != 0;
    });
    that.setData({
      selectRegionDone: doneStatus
    })
  },
  //打开省市区弹窗
  chooseRegion() {
    console.log('this.data.regionType', this.data.regionType);
    this.setData({
      openSelectRegion: !this.data.openSelectRegion
    });
    //设置区域选择数据
    let address = this.data.address;
    if (address.province > 0 && address.city > 0 && address.area > 0) {
      let selectRegionList = this.data.selectRegionList;
      selectRegionList[0].area_id = address.province;
      selectRegionList[0].area_name = address.province_name;
      selectRegionList[0].parent_id = 0;

      selectRegionList[1].area_id = address.city;
      selectRegionList[1].area_name = address.city_name;
      selectRegionList[1].parent_id = address.province;

      selectRegionList[2].area_id = address.area;
      selectRegionList[2].area_name = address.area_name;
      selectRegionList[2].parent_id = address.city;
      this.setData({
        selectRegionList: selectRegionList,
        regionType: 3
      });
      this.getRegionList(address.city, 3);
    } else {
      this.setData({
        selectRegionList: [
          { area_id: 0, area_name: '省份', parent_id: 0, type: 1 },
          { area_id: 0, area_name: '城市', parent_id: 0, type: 2 },
          { area_id: 0, area_name: '区县', parent_id: 0, type: 3 }
        ],
        regionType: 1
      })
      this.getRegionList(0, 1);
    }
    this.setRegionDoneStatus();
  },
  onLoad: function (options) {
    that = this;
    // 页面初始化 options为页面跳转所带来的参数
    console.log(options)
    if (options.id) {
      this.setData({
        addressId: options.id
      });
      this.getAddressDetail();
    } else {
      this.getRegionList(0, 1);
    }
  },
  onReady: function () {

  },
  //设置省市区选择步骤
  selectRegionType(event) {
    console.log('this.data.regionType', this.data.regionType);
    let i = event.target.id;                //当前索引
    let type = event.target.dataset.type;   //当前类型
    let regionType = this.data.regionType;  //全局regionType：1省、2市、3区
    let selectRegionList = that.data.selectRegionList;
    //判断:不可点击（当前类型、当前类型>全局regionType 且 当前parent_id==0）
    if (type == regionType || (type > regionType && selectRegionList[i].parent_id == 0)) {
      //拦截点击
      return false;
    }
    //允许点击
    this.setData({
      regionType: type
    })
    let selectRegionItem = selectRegionList[i];
    this.getRegionList(selectRegionItem.parent_id, type);
    this.setRegionDoneStatus();
  },
  //设置选中当前点击
  selectRegion(event) {
    console.log('this.data.regionType', this.data.regionType);
    let i = event.target.id;  //省市区列表的索引
    let regionItem = this.data.regionList[i]; //当前选中
    let regionType = regionItem.type;   //当前选中的类型
    let selectRegionList = this.data.selectRegionList;
    selectRegionList[regionType - 1] = regionItem;
    if (regionType != 3) {
      that.setData({
        //selectRegionList: selectRegionList,
        regionType: regionType + 1
      })
      that.getRegionList(regionItem.area_id, regionType + 1);
    }
    //重置下级区域为空
    selectRegionList.map((item, index) => {
      if (index > regionType - 1) {
        item.area_id = 0;
        item.area_name = (index == 1) ? '城市' : '区县';
        item.parent_id = 0;
      }
      return item;
    });
    that.setData({
      selectRegionList: selectRegionList
    })

    that.setData({
      regionList: that.data.regionList.map(item => {
        //标记已选择的
        if (that.data.regionType == item.type && that.data.selectRegionList[that.data.regionType - 1].area_id == item.area_id) {
          item.selected = true;
        } else {
          item.selected = false;
        }
        return item;
      })
    });
    this.setRegionDoneStatus();
  },
  //确定
  doneSelectRegion() {
    if (this.data.selectRegionDone === false) {
      return false;
    }
    let address = this.data.address;
    let selectRegionList = this.data.selectRegionList;
    address.province = selectRegionList[0].area_id;
    address.city = selectRegionList[1].area_id;
    address.area = selectRegionList[2].area_id;
    address.province_name = selectRegionList[0].area_name;
    address.city_name = selectRegionList[1].area_name;
    address.area_name = selectRegionList[2].area_name;
    address.full_region = selectRegionList.map(item => {
      return item.area_name;
    }).join('');

    this.setData({
      address: address,
      openSelectRegion: false
    });
  },
  //取消
  cancelSelectRegion() {
    this.setData({
      openSelectRegion: false,
      regionType: this.data.selectRegionDone ? 3 : 1
    });
  },
  //接口获取省市区列表
  getRegionList(regionId, type) {
    let regionType = that.data.regionType;
    util.request(api.RegionList, { parentId: regionId }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          regionList: res.data.map(item => {
            //标记已选择的
            if (that.data.selectRegionList[regionType - 1].area_id == item.area_id) {
              item.selected = true;
            } else {
              item.selected = false;
            }
            item.type = type;
            return item;
          })
        });
      }
    });
  },
  //取消按钮
  cancelAddress() {
    wx.navigateBack({
      url: '/pages/ucenter/address/address',
    })
  },
  //保存按钮
  saveAddress() {
    let address = this.data.address;
    if (address.accept_name == '') {
      util.showErrorToast('请输入姓名');
      return false;
    }
    if (address.mobile == '') {
      util.showErrorToast('请输入手机号码');
      return false;
    }
    if (address.area == 0) {
      util.showErrorToast('请输入省市区');
      return false;
    }
    if (address.address == '') {
      util.showErrorToast('请输入详细地址');
      return false;
    }

    util.request(api.AddressSave, {
      id: address.id,
      accept_name: address.accept_name,
      mobile: address.mobile,
      province: address.province,
      city: address.city,
      area: address.area,
      address: address.address,
      is_default: address.is_default,
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        wx.navigateBack({
          url: '/pages/ucenter/address/address',
        })
      }
    });
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})